#include <iostream>
#include <string>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "ThreadPool/log.hpp"

void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " port\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[1]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    int sock = 0;
    std::string message;
    bool flag = false;
    while (true)
    {
        if (!flag)  // 没有连接  先连接
        { // 1.创建套接字
            sock = socket(AF_INET, SOCK_STREAM, 0);
            if (sock < 0)
            {
                logMessage(FATAL, "socket error, %d: %s", errno, strerror(errno));
                exit(2);
            }

            // 2.客户端不需要bind的
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(serverport);
            server.sin_addr.s_addr = inet_addr(serverip.c_str());

            if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
            {
                logMessage(FATAL, "connect error, %d: %s", errno, strerror(errno));
                exit(3);
            }

            logMessage(NORMAL, "connect success");
            flag = true;
        }

        std::cout << "请输入# ";
        std::getline(std::cin, message);
        if (message == "quit")  break;

        ssize_t s = send(sock, message.c_str(), message.size(), 0);  // sendto是udp使用的, send是tcp使用的
        if (s > 0)
        {
            char buffer[1024];
            ssize_t s =  recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                std::cout << "server 回显: " << buffer << std::endl;
            }
            else if(s == 0)
            {
                flag = false;
                close(sock);
            }
        }
        else
        {
            flag = false;
            close(sock);
        }
    }
    return 0;
}